package com.rc.saas.tenant.controller.finance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.constant.CommonConstant;
import com.rc.saas.tenant.common.utils.DateUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.elec.ElecStationExample;
import com.rc.saas.tenant.model.rc.RcOperatorAccount;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.rc.RcOperatorAccountSearch;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.rc.RcOperatorAccountService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.order.OrderResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 财务报表控制器
 * @author quankl
 */
@Controller
@RequestMapping("/financialStatement")
public class FinancialStatementController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(FinancialStatementController.class);

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PlatformAreaService areaService;

    /**
     * 跳转 充电加盟页面
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        return "/templates/finance/statementChart";
    }


    /**
     * 获取充电加盟数据
     * @param stationName 站点名称
     * @param provinceId  省份ID
     * @param cityId  城市ID
     * @param areaId  区/县ID
     * @param bizType  类型（0:自营充电，1:加盟商）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public TResponse getData(@RequestParam("stationName") String stationName,
                             @RequestParam("provinceId")String provinceId,
                             @RequestParam("cityId")String cityId,
                             @RequestParam("areaId")String areaId,
                             @RequestParam("bizType")String bizType) {
        if ("0".equals(bizType)&& StringUtils.isEmpty(stationName)){
            bizType = null;
        }
        Map<String,Object> data = orderInfoService.getStatementData(stationName,provinceId,cityId,areaId,bizType);
        return TResponse.SUCCESS_DATA(data);
    }

    /**
     * 导出文件
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(@RequestParam("stationName") String stationName,
                            @RequestParam("provinceId")String provinceId,
                            @RequestParam("cityId")String cityId,
                            @RequestParam("areaId")String areaId,
                            @RequestParam("bizType")String bizType,
                            HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            Map<String,Object> data = orderInfoService.getStatementData(stationName,provinceId,cityId,areaId,bizType);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("财务报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<StatementData> list = new ArrayList<StatementData>();
            if(!CollectionUtils.isEmpty(data)){
                list.add(new StatementData((Long)data.get("orderTotal"),(BigDecimal)data.get("powerTotal"),(BigDecimal)data.get("amountTotal")));
            }
            EasyExcel.write(response.getOutputStream(), StatementData.class).sheet(("0".equals(bizType)?"充电":"加盟")+"-财务报表").doWrite(list);
            return null;
        } catch (Exception e) {
            logger.error("导出财务报表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }
}

class StatementData implements Serializable {
    @ExcelProperty(value = "订单量",index = 0)
    private Long orderTotal;
    @ExcelProperty(value = "充电量",index = 1)
    private BigDecimal powerTotal;
    @ExcelProperty(value = "累计收入",index = 2)
    private BigDecimal amountTotal;

    public StatementData(Long orderTotal, BigDecimal powerTotal, BigDecimal amountTotal) {
        this.orderTotal = orderTotal;
        this.powerTotal = powerTotal;
        this.amountTotal = amountTotal;
    }

    public Long getOrderTotal() {
        return orderTotal;
    }

    public void setOrderTotal(Long orderTotal) {
        this.orderTotal = orderTotal;
    }

    public BigDecimal getPowerTotal() {
        return powerTotal;
    }

    public void setPowerTotal(BigDecimal powerTotal) {
        this.powerTotal = powerTotal;
    }

    public BigDecimal getAmountTotal() {
        return amountTotal;
    }

    public void setAmountTotal(BigDecimal amountTotal) {
        this.amountTotal = amountTotal;
    }
}
